import { ref, Ref, watch } from 'vue';

export interface CountRange {
  min: number;
  max: number;
}

interface Result {
  current: Ref<number>;
  // minus: (num: number) => void;
  // plus: (num: number) => void;
  // set: (num: number) => void;
  minus: Function;
  plus: Function;
  set: Function;
  reset: () => void;
}

export function useCount(init: number, range: CountRange): Result {
  const current = ref(init);
  const minus = (num: number) => {
    current.value -= num;
  };
  const plus = (num: number) => {
    current.value += num;
  };
  // 设置指定值，如果超过最大最小值侧用最大或最小值
  const set = (num: number) => {
    console.log(num);
    current.value = num;
  };
  const reset = () => { // 重置
    current.value = init;
  };

  // 侦听 current 变量
  watch(current, (newVal: number, oldVal: number) => {
    if (newVal === oldVal) return;
    if (newVal < +range.min) {
      current.value = +range.min;
    } else if (newVal > +range.max) {
      current.value = +range.max;
    }
  });

  return { current, minus, plus, set, reset };
}